﻿using AlibabaCloud.SDK.Dysmsapi20170525;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using PMRC.API.Helper;
using PMRC.API.Server.Interface;

namespace PMRC.API.Server.Implements
{
    public class SmsService : ISmsService
    {
        private readonly ILogger<SmsService> _logger;
        private readonly Client _client;
        private readonly IConfiguration _configuration;
        public SmsService(
            ILogger<SmsService> logger,
            IConfiguration configuration
            )
        {
            _configuration = configuration;
            _logger = logger;
            _client = new Client(new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = _configuration.GetValue<string>("SmsSettings:AccessKeyId"),
                AccessKeySecret = _configuration.GetValue<string>("SmsSettings:AccessKeySecret"),
                Endpoint = "dysmsapi.aliyuncs.com"
            });
        }

        public async Task<bool> SendVerificationCodeAsync(string phoneNumber, string code)
        {
            var request = new SendSmsRequest();
            request.PhoneNumbers = phoneNumber;
            request.SignName = _configuration.GetValue<string>("SmsSettings:SignName");
            request.TemplateCode = _configuration.GetValue<string>("SmsSettings:TemplateCode");
            request.TemplateParam = JsonHelper.Serialize(new Dictionary<string, string>() { { "code", code } });
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            var response = await _client.SendSmsWithOptionsAsync(request, runtime);
            //_logger.LogInformation("手机号：{0},验证码:{1},发送结果:{2}", phoneNumber, code, JsonHelper.Serialize(response));
            if (response.Body.Code == "OK")
            {
                _logger.LogInformation("手机号：{0},验证码:{1},发送成功", phoneNumber, code);
                return true;
            }
            _logger.LogWarning("手机号：{0},验证码:{1},发送失败！，错误原因：{2}", phoneNumber, code, response.Body.Message);
            return false;
        }
    }
}
